#include "sprite.h"

#include <iostream>
#include <cmath>

#include "gamedata.h"

const Vector2f WALL_LEFT = Vector2f(-1, 0);
const Vector2f WALL_RIGHT = Vector2f(1, 0);
const Vector2f WALL_TOP = Vector2f(0, 1);
const Vector2f WALL_BOTTOM = Vector2f(0, -1);

Sprite::Sprite(const string& n, AbstractFactory* factory) :
  Drawable(Vector2f(Gamedata::getInstance().getXmlInt(n+"X"),
                    Gamedata::getInstance().getXmlInt(n+"Y")), 
           Vector2f(Gamedata::getInstance().getXmlInt(n+"Xspeed"),
                    Gamedata::getInstance().getXmlInt(n+"Yspeed")),
           Vector2f(Gamedata::getInstance().getXmlInt(n+"MaxXspeed"),
                    Gamedata::getInstance().getXmlInt(n+"MaxYspeed"))
                    ), 
  name(n),
  frame(factory->getFrame(name)),
  visible(true),
  owner( NULL )
{ }

Sprite::Sprite(const Vector2f& pos, const Vector2f& vel, 
               const string& n, const Frame* fm) :
  Drawable(pos, vel, 
           Vector2f(Gamedata::getInstance().getXmlInt(n+"MaxXspeed"),
                    Gamedata::getInstance().getXmlInt(n+"MaxYspeed"))
  ), 
  name(n),
  frame(fm),
  visible(true),
  owner( NULL )
{ }

Sprite::Sprite(const Vector2f& pos, const Vector2f& vel, const string& n, AbstractFactory* factory) :
	Drawable(pos, vel, 
		Vector2f(Gamedata::getInstance().getXmlInt(n+"MaxXspeed"),
		         Gamedata::getInstance().getXmlInt(n+"MaxYspeed"))
	), 
	name(n),
	frame(factory->getFrame(name)),
	visible(true),
	owner( NULL )
{
	
}

Sprite::Sprite(const Sprite& s) :
	Drawable(s.getPosition(), s.getVelocity(), s.getMaxVelocity()), 
	name( s.getName() ),
	frame(s.frame),
	visible(s.visible),
	owner(s.owner)
{
	
}

Sprite& Sprite::operator=(const Sprite& rhs)
{
	setName( rhs.getName() );
	setPosition(rhs.getPosition());
	setVelocity(rhs.getVelocity());
	setMaxVelocity(rhs.getMaxVelocity());
	frame = rhs.frame;
	visible = rhs.visible;
	owner = rhs.owner;
	return *this;
}

void Sprite::draw() const
{
	if(!visible)
		return;

	Uint32 x = static_cast<Uint32>(X());
	Uint32 y = static_cast<Uint32>(Y());
	frame->draw(x, y); 
}

unsigned Sprite::getPixel(Uint32 i, Uint32 j) const
{ 
	Uint32 x = static_cast<Uint32>(X());
	Uint32 y = static_cast<Uint32>(Y());
	x = i - x;
	y = j - y;
	Uint32 *pixels = static_cast<Uint32 *>(frame->getSurface()->pixels);
	return pixels[ ( y * frame->getWidth() ) + x ];
}

int Sprite::getDistance(const Sprite *obj) const
{ 
  return hypot(X()-obj->X(), Y()-obj->Y());
}

void Sprite::update(Uint32 ticks)
{
	ticks = 0;
}

void Sprite::handleMouseMotion()
{
	
}

void Sprite::shoot()
{
	
}
